package lm.concurrency.day6;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 14:41 2024/11/8
 */
@Slf4j
public class ExecutorsTest {
    public static void main(String[] args) {
        //FixedThreadPoolTest();
        CachedThreadPoolTest();
        //SingleThreadExecutorTest();
    }

    private static void SingleThreadExecutorTest() {
        ExecutorService threadPool;
        threadPool = Executors.newSingleThreadExecutor();
//        threadPool = Executors.newSingleThreadExecutor(new ThreadFactory() {
//            private AtomicInteger integer = new AtomicInteger(1);
//            @Override
//            public Thread newThread(Runnable r) {
//                return new Thread(r,"mypool3-"+integer.getAndIncrement());
//            }
//        });
        threadPool.execute(()->{
            log.debug("1");
            int i = 1/0;
        });
        threadPool.execute(()->{
            log.debug("2");
        });
        threadPool.execute(()->{
            log.debug("3");
        });
    }

    private static void CachedThreadPoolTest() {
        ExecutorService threadPool;
        //带缓冲区的线程池
        threadPool = Executors.newCachedThreadPool( new ThreadFactory() {
            private AtomicInteger integer = new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"mypool2-"+integer.getAndIncrement());
            }
        });

        threadPool.execute(()->{
            log.debug("1");
        });
        threadPool.execute(()->{
            log.debug("2");
        });
        threadPool.execute(()->{
            log.debug("3");
        });
    }

    private static void FixedThreadPoolTest() {
        ExecutorService threadPool;
        //固定大小线程池 使用默认ThreadFactory
        // threadPool = Executors.newFixedThreadPool(2);
        //固定大小线程池  使用自定义的ThreadFactory
        threadPool = Executors.newFixedThreadPool(2, new ThreadFactory() {
            private AtomicInteger integer = new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"mypool1-"+integer.getAndIncrement());
            }
        });

        threadPool.execute(()->{
            log.debug("1");
            int i = 1/0;
        });
        threadPool.execute(()->{
            log.debug("2");
        });
        threadPool.execute(()->{
            log.debug("3");
        });
        threadPool.shutdown();
        //太阳天或下雨天 一个人的咖啡店 找一个很想你舒服的角落 看着行人肩靠肩 慢慢转开我视线
        //有个女孩让我好像念  我的心 已经 飞到这个城市的另一边  想开着你 我爱的脸  把心里的誓言 都对你说
        //那马路上 天天都在塞 每个人天天在忍耐 没有你日子 很黑白  我想这样就是恋爱  我想要你在我身边 分享生命中的一切
    }
}
